﻿using Engine;
using Game;
namespace Mekiasm.FluidElement
{
    public class ElectricPumpFluidElement : Common.FluidElement
    {
        public bool WaterPointVailid;
        public Point3 WaterPoint;
        public ElectricPumpFluidElement(int x, int y, int z) : base(x, y, z)
        {
        }
        //抽取流体方块
        public virtual void GetWater()
        {
            var Component = Instance.Machine;
            if (Component.Power < Component.InputPowerLimit)
            {
                return;
            }
            for (int i = 0; i < Component.Slots.Count; i++)
            {
                ComponentEnergyMachine.Slot slot = Component.Slots[i];
                if (Time.PeriodicEvent(2.0, 0.0) && slot.FuelAmount < slot.FuelCapacity && Component.Power >= Component.OutputPowerLimit)
                {//有电可用
                 //获取朝向
                    if (WaterPointVailid)
                    {
                        int vc = ILibrary.SubsystemTerrain.Terrain.GetCellValueFast(WaterPoint.X, WaterPoint.Y, WaterPoint.Z);
                        int b = Terrain.ExtractContents(vc);

                        if (BlocksManager.Blocks[b] is FluidBlock)
                        {
                            long d = GetAvaiablePower(slot.FuelAmount, Component.OutputFluidAmountLimit, slot.FuelCapacity, slot.FuelCapacity);
                            d *= 20;
                            if (Component.AddFuel(i, ComponentEnergyMachine.FuelType.Fliud, d, vc))
                            {
                                Component.Power -= Component.InputPowerLimit;
                                ILibrary.SubsystemTerrain.ChangeCell(WaterPoint.X, WaterPoint.Y, WaterPoint.Z, 0);
                            }
                        }
                        else
                        {
                            WaterPointVailid = false;
                        }

                    }
                    else
                    {
                        for (int j = 0; j < 8; j++)
                        {
                            Point3 point3 = ILibrary.GetNeiborPoint(Point, j);//获取周围一格方块
                            int vc = ILibrary.SubsystemTerrain.Terrain.GetCellValueFast(point3.X, point3.Y, point3.Z);
                            int b = Terrain.ExtractContents(vc);
                            if (BlocksManager.Blocks[b] is FluidBlock)
                            {
                                WaterPoint = point3;
                                WaterPointVailid = true;
                            }
                        }
                    }
                }
            }
        }

        public override bool Simulate()
        {
            GetWater();
            ChargeOrDischargeItem(0);
            return base.Simulate();
        }

    }
}
